from curse import ascii
from xml.dom import minidom

class Converter():
    def loadXML(self, xml):
        minidom.parseString(xml)
    
    @classmethod
    def _safeJSON(cls, sIn):
        sbOut = ''
        
        for ch in sIn:
            if ch == "\"" or ch == "\\" or ch == "/":
                sbOut += "\\"
            elif ch == "\b" or ch == "\f" or ch == "\n" or ch == "\r" or ch == "\t":
                ich = ord(ch)
                xch = hex(ich)
                uch = `xch`
                while len(uch) < 4:
                    uch = '0' + uch
                
                uch = '0x' + uch
                sbOut += uch
                continue
            
            sbOut += ch
        
        return sbOut
 
    @classmethod
    def _outputNode(cls, childName, alChild, sbJSON, showNodeName):
        if alChild == None:
            if showNodeName:
                sbJSON += "\"" + _safeJSON(childName) + "\": "
            sbJSON += "null"
        elif isinstance(alChild, str):
            if showNodeName:
                sbJSON += "\"" + _safeJSON(childName) + "\": "
            sChild = alChild.strip()
            sbJSON += "\"" + _safeJSON(sChild) + "\""
        else:
            sbJSON = _xmlToJSONnode(sbJSON, alChild, showNodeName)
        
        sbJSON += ", "
        
        return sbJSON
        
    @classmethod
    def _storeChildNode(cls, childNodeNames, nodeName, nodeValue):
        if isinstance(nodeValue, minidom.Element):
            cnode = nodeValue
      

#private static void StoreChildNode(SortedList childNodeNames, string nodeName, object nodeValue)
#{
#    // Pre-process contraction of XmlElement-s
#    if (nodeValue is XmlElement)
#    {
#        // Convert  <aa></aa> into "aa":null
#        //          <aa>xx</aa> into "aa":"xx"
#        XmlNode cnode = (XmlNode)nodeValue;
#        if( cnode.Attributes.Count == 0)
#        {
#            XmlNodeList children = cnode.ChildNodes;
#            if( children.Count==0)
#                nodeValue = null;
#            else if (children.Count == 1 && (children[0] is XmlText))
#                nodeValue = ((XmlText)(children[0])).InnerText;
#        }
#    }
#    // Add nodeValue to ArrayList associated with each nodeName
#    // If nodeName doesn't exist then add it
#    object oValuesAL = childNodeNames[nodeName];
#    ArrayList ValuesAL;
#    if (oValuesAL == null)
#    {
#        ValuesAL = new ArrayList();
#        childNodeNames[nodeName] = ValuesAL;
#    }
#    else
#        ValuesAL = (ArrayList)oValuesAL;
#    ValuesAL.Add(nodeValue);
#}